import Ux from 'ux';

const dialog = (reference) => ({
    add: (params = {}, config = {}) => {
        let request = Ux.valueRequest(params);
        request = Ux.valueValid(request);
        return Ux.ajaxPost(config.uri, request)
            .then(Ux.ajax2Message(reference, config.dialog))
            .then(response => {
                Ux.of(reference)._.close(response);
                return Ux.promise(response);
            })
    },
    save: (params = {}, config = {}) => {
        let request = Ux.valueRequest(params);
        request = Ux.valueValid(request);
        return Ux.ajaxPut(config.uri, request)
            .then(Ux.ajax2Message(reference, config.dialog))
            .then(response => {
                Ux.of(reference)._.close(response);
                return Ux.promise(response);
            })
    },
    saveRow: (params = {}, config = {}) => {
        let request = Ux.valueRequest(params);
        const {rxRow} = reference.props;
        if (Ux.isFunction(rxRow)) {
            const {$mode = ""} = reference.props;
            if (Ux.Env.FORM_MODE.ADD === $mode && !config.close) {
                /*
                 * 重置当前表单
                 */
                const {reset = []} = config;
                Ux.formReset(reference, reset);
                /*
                 * 根据初始值需要得到一条新数据
                 */
                let {$inited = {}} = reference.props;
                $inited = Ux.clone($inited);
                $inited.key = Ux.randomUUID();
                /*
                 * 变更 key
                 */
                rxRow(request, {
                    $submitting: false, // 关闭提交
                    $inited,            // 继续添加，处于添加模式比较特殊
                });
            } else {
                rxRow(request, {
                    $visible: false, // 关闭窗口
                    $submitting: false, // 关闭提交
                });
            }


            /*
             * 提交专用（防止重复提交问题）
             */
            Ux.of(reference).load(false).done();
            // reference.setState({$loading: false});
        } else {
            throw new Error("[ Ux ] 缺失核心函数 rxRow()");
        }
        return Ux.promise(request);
    },
    saveSelected: (data = []) => {
        const {rxRows} = reference.props;
        if (Ux.isFunction(rxRows)) {
            rxRows(data, {
                $visible: false, // 关闭窗口
            })
        } else {
            throw new Error("[ Ux ] 缺失核心函数 rxRow()");
        }
    }
});
export default {
    dialog,
}
